package com.atguigu.jwt.util;

import com.atguigu.jwt.entity.Member;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * @author codingBee
 * @since 2020/12/14/7:47
 */
public class JwtUtils {
    //过期时间
    public static final long EXPIRE = 1000 * 60 * 30; //单位毫秒
    public static final String APP_SECRET="79e7c69681b8270162386e6daa53d1dc"; // app secret
    public static String genJwt(Member member) {
        //1.创建 JwtBuilder 对象
        JwtBuilder jwtBuilder = Jwts.builder();
        //2.第一部分：JWT 头 header
        jwtBuilder.setHeaderParam("alg", "HS256"); //签名算法
        jwtBuilder.setHeaderParam("typ", "JWT"); //令牌类型
        //3.第二部分：有效载荷 playLoad
        //3.1默认字段
        jwtBuilder.setId("1");//唯一身份标识（通常是随机数）
        jwtBuilder.setSubject("guli-user");//令牌的主题
        jwtBuilder.setIssuedAt(new Date());
        jwtBuilder.setExpiration(new Date(System.currentTimeMillis()+EXPIRE)); //过期时间
        //3.2私有字段
        jwtBuilder.claim("id",member.getId()).claim("nickName",member.getNickname()).claim("avatar",member.getAvatar());

        //4.第三部分：签名哈希 VERIFY SIGNATURE
        jwtBuilder.signWith(SignatureAlgorithm.HS256,APP_SECRET);

        //5.将上面三部分连接起来
        String jwt = jwtBuilder.compact();//生成签名hash字符串
        return jwt;
    }

    public static Claims checkJwt(String jwtToken){
        JwtParser parser= Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        JwsHeader header = claimsJws.getHeader();
        Claims body = claimsJws.getBody();
        String signature = claimsJws.getSignature();
        System.out.println(header);
        System.out.println(body);
        System.out.println(signature);
        return body;
    }
}
